import time,datetime,json
from 组件.notice import show_notification_thread
from 组件.sqlite import SimpleSQLite
from 公共函数 import get_stock,need_notice,add_notice,update_notice
from 基础配置 import settings

stock_span = {stock["all_code"]: stock["span"] for stock in settings.STOCK_CODE}
stock_down = {stock["all_code"]: stock["down"] for stock in settings.STOCK_CODE}
day_look = settings.DAY_LOOK
from xtquant import xtdata
xtdata.enable_hello = False



def is_after_12pm():
    """判断上午或者下午,如果day_look小于3,那11点开始就使用午盘规则"""
    now = datetime.datetime.now().time()  # 获取当前时间（只取时间部分）
    if day_look<=3:
        noon = datetime.time(12, 0, 0)  # 创建12点的时间对象
    else:
        noon = datetime.time(12, 0, 0)  # 创建12点的时间对象
    return now > noon

def order_watch(self):
    ##买入检测

    ##撤单检测
    notice = False
    filled_orders_sorted, no_filled_orders, stocks = self.get_orders()  # 修改这里，接收3个返回值
    print("未成交挂单检测运行中......")
    for order in no_filled_orders:
        stock_code = order.stock_code
        msg = f"订单 {order.order_sysid}"
        if stock_code == "000838.SZ":
            return

        if order.order_type == 23:
            # 检测n分钟没买入撤销
            if stock_code == "513060.SH" or stock_code == "513130.SH" or stock_code == "513130.SH":
                n = 10
            else:
                n = 10
            current_time = datetime.datetime.now().timestamp()  # 当前时间戳
            time_diff = current_time - order.order_time  # 计算时间差（秒）

            if time_diff > n:
                print(f"{stock_code}检测{n}秒没买入撤销挂单")
                ##这里需要拿到remark判断level是否是0，0才会提高一挡位买
                remark_str = order.order_remark
                try:
                    remark = json.loads(remark_str)
                    level = remark.get("level", 1)
                    if level == 100:
                        print(f"{stock_code}检测{n}秒没买入高一级别买入")
                        new_price = float(order.price) + 0.001
                        new_remark = {
                            "level": 1,
                            "macd": remark.get("macd", ""),
                            "rsi": remark.get("rsi", ""),
                            "atr": remark.get("atr", ""),
                        }
                        new_remark_string = json.dumps(new_remark, ensure_ascii=False)

                        self.mod_order_price(order.order_sysid, new_price,new_remark_string)
                except json.JSONDecodeError as e:
                    pass
                except KeyError as e:
                    pass
                self.cancel_order(order.order_sysid)


        else:
            ##检测5分钟没卖出则下降一档卖出
            span = stock_span.get(stock_code)
            current_time = datetime.datetime.now().timestamp()  # 当前时间戳
            time_diff = current_time - order.order_time  # 计算时间差（秒）
            if time_diff > 300:
                new_price = float(order.price) - float(span)
                print(f"{stock_code}检测5分钟没卖出则下降一档卖出")
                self.mod_order_price(order.order_sysid,new_price)

            ##新的方案，分两笔买入，一开始第一笔止损和第二笔止损的都是固定的。
            ##默认都给3挡,如果触达3档全部止损
            ##1.获取当前价格,如果有问题需要去除使用xtdata
            current_price = get_last_price(xtdata,stock_code)
            if current_price>0:
                now_price = current_price
            else:
                data = get_stock(stock_code)
                now_price = data["now_price"]
            print(f"订单 {order.order_sysid}挂单价格{order.price},检测最新迅投价格 {current_price},检测最新本地价格 {now_price}")
            ##获取订单order_remark信息
            remark_str = order.order_remark
            buy_id = 0
            sell_type = 1
            order_type = 1
            buy_price = 0
            down_price = 0
            # print(remark_str)

            try:
                remark = json.loads(remark_str)
                buy_id = remark.get("buy_id", 0)
                sell_type = remark.get("sell_type", 1)
                order_type = remark.get("order_type", 1)
                buy_price = remark.get("buy_price", 0)

                print(f"买入价格:{buy_price}")
            except json.JSONDecodeError as e:
                pass
            except KeyError as e:
                pass

            if buy_id:
                if is_after_12pm():
                    up = 2
                else:
                    ##如果是上午可以设置为0.3%
                    up = 3

                if sell_type==1:##1为普通单2为区间单
                    if order_type == 1:
                        if span == 0.002:
                            down_price = float(buy_price) - float(span * up)
                        else:
                            down_price = float(buy_price) - float(span * up)
                    if order_type == 2:
                        if span == 0.002:
                            down_price = float(buy_price) - float(span * up)
                        else:
                            down_price = float(buy_price) - float(span * up)
                        ##查询相同buy_id的另外一笔是否成交
                        if check_other_order_filled(filled_orders_sorted, buy_id, order.order_sysid):
                            down_price = float(buy_price) - float(span * (up-1))
                if sell_type==2:
                    down_price = float(buy_price) - float(span * 2)

                # down_price = float(buy_price) - float(span * 3)

                print(f"订单 {order.order_sysid}止损价格 {down_price}")

                if float(now_price) <= float(down_price):
                    notice = True
                    msg += "跌幅警告,"
                    print(f"平仓订单 {order.order_sysid}买入价格{buy_price},最新价格 {now_price}止损{down_price}")
                    self.modify_to_market_order(order.order_sysid)
            else:
                # 当buy_id为0或无效时，使用默认止损逻辑
                # 这里可以根据需要添加默认的止损策略
                print(f"订单 {order.order_sysid} 缺少有效的buy_id信息，跳过止损检查")

        # 在循环外部统一处理通知逻辑
        if notice:
            need = need_notice(order.order_sysid,msg)
            if need ==0:
                add_notice(order.order_sysid,msg)
            if need==1:
                print(msg)
                update_notice(order.order_sysid,msg)
                # show_notification_thread("撤单提醒", msg)
        else:
            print("挂单检测正常")
def get_last_price(xtdata,stock_code):
    start_time = time.time()  # 记录开始时间
    current_price = 0
    # 获取最新tick数据
    tick_data = xtdata.get_full_tick([stock_code])
    # 安全地获取价格数据
    if stock_code in tick_data:
        stock_data = tick_data[stock_code]
        # 检查数据结构并安全获取价格
        if isinstance(stock_data, dict):
            # 如果返回的是字典格式
            current_price = stock_data.get('lastPrice', 0)
        elif isinstance(stock_data, list) and len(stock_data) > 0:
            # 如果返回的是列表格式
            if isinstance(stock_data[0], dict):
                current_price = stock_data[0].get('lastPrice', 0)
            else:
                current_price = stock_data[0] if stock_data[0] else 0
    
    end_time = time.time()  # 记录结束时间
    execution_time = (end_time - start_time) * 1000  # 转换为毫秒
    print(f"get_last_price 执行时间: {execution_time:.2f} 毫秒")
    return current_price
def check_other_order_filled(filled_orders, buy_id, current_order_sysid):
    try:
        # 查找相同buy_id的其他已成交订单
        for order in filled_orders:
            if order.order_sysid == current_order_sysid:
                continue  # 跳过当前订单
                
            try:
                # 解析订单备注信息
                remark_str = order.order_remark
                if remark_str:
                    remark = json.loads(remark_str)
                    order_buy_id = remark.get("buy_id")
                    
                    # 如果找到相同buy_id的订单且已成交
                    if order_buy_id == buy_id:
                        print(f"找到相同buy_id {buy_id} 的订单 {order.order_sysid} 已成交")
                        return True
            except (json.JSONDecodeError, KeyError) as e:
                # 如果解析备注失败，跳过这个订单
                continue
                
        print(f"未找到相同buy_id {buy_id} 的其他已成交订单")
        return False
        
    except Exception as e:
        print(f"查询相同buy_id订单时出错: {e}")
        return False

if __name__ == "__main__":
    price = get_last_price(xtdata,stock_code="513310.SH")
    print(price)